package xyz.naokeziteng.data_structure.graph_theory;

import java.util.Arrays;

/**
 * @author hawk
 * @date 2022/10/8
 * @desc s-t的路径
 **/
public class DfsPath {

    private Graph G;
    private boolean[] visited;
    private int[] pre;
    //源点
    private int s;
    //终点
    private int t;

    /**
     * @param G 图
     * @param s 源
     * @param t 终点
     */
    public DfsPath(Graph G, int s, int t) {
        G.validateVertex(s);
        G.validateVertex(t);
        this.s = s;
        this.G = G;
        this.t = t;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];
        Arrays.fill(this.pre, -1);
        dfs(s, s);
    }

    //深度优先遍历
    private boolean dfs(int v, int parent) {
        visited[v] = true;
        pre[v] = parent;
        if (v == t) {
            return true;
        }
        for (int w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isConnected() {
        return visited[t];
    }

    //寻找路径
    public String path() {
        if (!isConnected()) {
            return "没有路径...";
        }
        StringBuilder sb = new StringBuilder();
        int p = t;
        while (p != s) {
            sb.append(p).append("<--");
            p = pre[p];
        }
        return sb.append(p).toString();
    }


    public static void main(String[] args) {
        DfsPath path = new DfsPath(new Graph("src/main/resources/g.txt"), 0, 6);
        System.out.println(path.path());
    }
}
